﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using pub.Interop;

namespace scheduler
{
    class CommonUtils
    {
        public static IntPtr FindTodoWindowForTodoList(string todoListFile)
        {
            var processes = new List<Process>(Process.GetProcessesByName("todo"));
            processes.AddRange(Process.GetProcessesByName("todo.vshost"));

            foreach (var process in processes)
            {
                var title = process.MainWindowTitle;
                var file = ExtractFileFromTitle(title);
                if (file == todoListFile)
                {
                    return process.MainWindowHandle;
                }
            }
            return IntPtr.Zero;
        }

        private static string ExtractFileFromTitle(string title)
        {
            var pos = title.IndexOf('[') + 1;
            if (pos == -1)
            {
                Debug.Print("bad todo window title: " + title);
                return null;
            }
            var pos2 = title.IndexOf(']', pos);
            if (pos2 == -1)
            {
                Debug.Print("bad todo window title: " + title);
                return null;
            }
            var file = title.Substring(pos, pos2 - pos);
            if (file.EndsWith(" *"))
            {
                file = file.Substring(0, file.Length - 2);
            }
            return file;
        }

        public static void ActivateWindow(IntPtr hwnd)
        {
            Win32.SetForegroundWindow(hwnd);
            if (Win32.IsIconic(hwnd))
            {
                Win32.ShowWindow(hwnd, Win32.SW_RESTORE);
            }
        }
    }
}
